<?php
/**
 * Created by PhpStorm.
 * User: feng
 * Date: 2018/1/17
 * Time: 10:35
 */

namespace Lib\Utils;

use Illuminate\Http\Request;

class ModelUtils
{
    public static function requestToModel(Request $request, $model)
    {
        $all = $request->all();
        $i = 0;
        $attributes = $model->getAttributes();
        if (!empty($attributes)) {
            foreach ($all as $key => $field) {
                if (array_key_exists($key, $attributes)) {
                    $model[$key] = $field;
                    $i++;
                }
            }
        } else {
            $columnlist = self::getTableColumns($model);
            foreach ($all as $key => $field) {
                if (in_array($key, $columnlist)) {
                    $model[$key] = $field;
                    $i++;
                }
            }
        }
        return $i;
    }
    public static function fuzzy($table,$column,$values){
        $keys = ArrayUtils::ToArray($values);
        foreach ($keys as $key) {
            $table = $table->where($column, 'like', '%' . $key . '%');
        }
        return $table;
    }
    public static function getTableColumns($model)
    {
        return $model->getConnection()->getSchemaBuilder()->getColumnListing($model->getTable());
    }

    public static function ModelSetToMapArray($modelset,$keyname,$valuename){
        $data=[];
        foreach ($modelset as $value)
        {
            $data[]=["name"=>$value->$keyname,"value"=>$value->$valuename];
        }
        return $data;
    }

    public static function ModelSetToArrayMap($modelset,$keyname){
        $data=[];
        if($modelset!=null)
            foreach ($modelset as $value)
            {
                $data[$value->$keyname][]=$value;
            }
        return $data;
    }
    public static function ModelSetToMap($modelset,$keyname,$valuename){
        $data=[];
        foreach ($modelset as $item)
        {
            $data[$item->$keyname]=$item->$valuename;
        }
        return $data;
    }


}